package com.wbdgj.base;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import com.wbdgj.http.HttpAdapter;
import com.wbdgj.http.HttpSerives;
import com.wbdgj.utils.LogUtils;
import com.wbdgj.utils.ToastUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import butterknife.ButterKnife;

/**
 * Created by cc on 16-7-9.
 */
public abstract class BaseFragment extends Fragment {
    protected View mainView;
    protected boolean isViewInitiated;
    protected boolean misVisibleToUser;
    protected boolean isDataInitiated;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    public HttpSerives getServer() {
        return HttpAdapter.getSerives();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //SkinManager.getInstance().register(getActivity());

        getActivity().getWindow()
                .getDecorView()
                .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getActivity().getWindow();
            WindowManager.LayoutParams localLayoutParams = getActivity().getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
        MIUISetStatusBarLightMode(getActivity().getWindow(), true);
        FlymeSetStatusBarLightMode(getActivity().getWindow(), true);

        if (getLayout() <= 0) {
            mainView = createMainView();
        } else {
            mainView = inflater.inflate(getLayout(), container, false);
        }
        if (mainView == null)
            throw new NullPointerException("hey,you forget set a view for " + getClass().getName());
        ButterKnife.bind(this, mainView);
        return mainView;
    }


    /**
     * 是否适应沉浸式
     *
     * @return
     */
    public boolean getFitSystem() {
        return false;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        onInit();
        if (onInitCompleteListener != null)
            onInitCompleteListener.onInitComplete();
//        if (getFitSystem()) {
//            setFitSystem();
//        }
    }

    protected View findViewById(@IdRes int id) {
        return mainView.findViewById(id);
    }

    @LayoutRes
    protected abstract int getLayout();

    protected View createMainView() {
        return null;
    }

    /**
     * 数据初始化
     */
    protected abstract void onInit();

    protected void launch(Class clazz) {
        startActivity(new Intent(getActivity(), clazz));
    }

    protected void launch(Class clazz, Intent intent) {
        intent.setClass(getActivity(), clazz);
        startActivity(intent);
    }

    protected void showToast(String msg) {
        ToastUtils.toastShort(msg);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //EventBus.getDefault().unregister(this);
    }

    OnInitCompleteListener onInitCompleteListener;

    public void setOnInitCompleteListener(OnInitCompleteListener onInitCompleteListener) {
        this.onInitCompleteListener = onInitCompleteListener;
    }

    public interface OnInitCompleteListener {
        void onInitComplete();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewInitiated = true;
        prepareFetchData();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        LogUtils.logi("------setUserVisibleHint当前加载的类名=" + getClass().getName());
//        LogUtils.logi("-----开始界面isVisibleToUser=" + isVisibleToUser);
//        LogUtils.logi("-----开始界面getUserVisibleHint()=" + getUserVisibleHint());
        if (getUserVisibleHint()) {
            this.misVisibleToUser = true;
            // LogUtils.logi("-----开始界面="+isVisibleToUser);
        } else {
            if (misVisibleToUser) {
                this.misVisibleToUser = false;
            }
        }
        //LogUtils.logi("-----isVisibleToUser的值="+isVisibleToUser);
        prepareFetchData(isVisibleToUser);
    }

    public abstract void fetchData();

    public boolean prepareFetchData() {
        return prepareFetchData(false);
    }

    public boolean prepareFetchData(boolean forceUpdate) {
        if (misVisibleToUser && isViewInitiated && (!isDataInitiated || forceUpdate)) {
            fetchData();
            // LogUtils.logi("----- getClass().getName()=" + forceUpdate);
            isDataInitiated = true;
            return true;
        }
        return false;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // SkinManager.getInstance().unregister(getActivity());
    }

    public static boolean MIUISetStatusBarLightMode(Window window, boolean dark) {
        boolean result = false;
        if (window != null) {
            Class clazz = window.getClass();
            try {
                int darkModeFlag = 0;
                Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
                Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
                darkModeFlag = field.getInt(layoutParams);
                Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
                if (dark) {
                    extraFlagField.invoke(window, darkModeFlag, darkModeFlag);//状态栏透明且黑色字体
                } else {
                    extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
                }
                result = true;
            } catch (Exception e) {

            }
        }
        return result;
    }


    public static boolean FlymeSetStatusBarLightMode(Window window, boolean dark) {
        boolean result = false;
        if (window != null) {
            try {
                WindowManager.LayoutParams lp = window.getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                window.setAttributes(lp);
                result = true;
            } catch (Exception e) {

            }
        }
        return result;
    }
}
